//
// Copyright (c) 2007 Rodrigo B. de Oliveira & Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using Milo.Ast;
using Milo.Compilation.Steps;
using Milo.Compilation.TypeSystem;

namespace Milo.Compilation
{
	public class IntroduceConversions : AbstractVisitorCompilerStep
	{
		public override void Run()
		{
			if (Errors.Count > 0) return;

			Visit(CompileUnit);
		}

		public override void LeaveReturnStatement(ReturnStatement node)
		{
			if (node.Expression == null) return;

			node.Expression = ConvertIfNeeded(GetEnclosingMethodReturnType(node), node.Expression);
		}

		private IType GetEnclosingMethodReturnType(ReturnStatement node)
		{
			return GetEntity((Method) node.GetAncestor(NodeType.Method)).ReturnType;
		}

		public override void LeaveMethodInvocationExpression(MethodInvocationExpression node)
		{
			if (node.Arguments.Count == 0 || TypeSystemHelpers.IsBuiltinFunction(node)) return;

			IParameter[] parameters = GetExpectedParameters(node);
			for (int i=0; i<node.Arguments.Count; ++i)
			{
				Expression currentArg = node.Arguments[i];
				Expression arg = ConvertIfNeeded(parameters[i].Type, currentArg);
				if (currentArg != arg)
				{
					node.Arguments.ReplaceAt(i, arg);
				}
			}
		}

		private IParameter[] GetExpectedParameters(MethodInvocationExpression node)
		{
			ICallableType callable = (ICallableType) GetExpressionType(node.Target);
			return callable.GetSignature().Parameters;
		}

		public override void LeaveBinaryExpression(BinaryExpression node)
		{
			node.Right = ConvertIfNeeded(GetExpressionType(node.Left), node.Right);
		}

		private Expression ConvertIfNeeded(IType expectedType, Expression e)
		{
			IType actualType = GetExpressionType(e);
			if (expectedType.IsAssignableFrom(actualType)
				&& !TypeSystemServices.RequiresBoxing(expectedType, actualType)) return e;

			return CodeBuilder.CreateCast(expectedType, e);
		}
	}
}